import React, { useState, useEffect } from 'react';

import { NavBar, Icon, Badge, Tabs, List, Toast, Button, Result, Card, ListView } from 'antd-mobile';

import { GetPublishedOrders, GetProducingApplies, GetWorkingOrders, GetHistoryOrders } from "@/api/tutor/orderList.js"

import { createForm } from 'rc-form'
import _ from 'lodash';

import { R, ORDER_STATUSES } from "@/assets/js/dict"
import { getHistoryOrdersOfParent } from "@/api/order/order.js";

import './orderList.scss';
import nodata from "@/assets/svg/nodata.svg"

const Item = List.Item;
const Brief = Item.Brief;

function OrderList (props) {
    let [userInfo] = useState(() => {
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        return userInfo
    });
    let [publishedOrdersList, setPublishedOrdersList] = useState([]);  // 报名订单
    let [pendingList, setPendingList] = useState([]);  // 待定与正在教学
    let [workingList, setWorkingList] = useState([]);  // 正在教学
    let [historyList, setHistoryList] = useState([]);  // 历史订单

    let [tabIndex, setTabIndex] = useState(0);  // tab 选中

    const tabs = [
        { title: <Badge text={publishedOrdersList.length}>报名订单</Badge> },
        { title: <Badge text={pendingList.length + workingList.length}>待定与正在教学</Badge> },
        { title: <Badge text={historyList.length}>历史订单</Badge> },
    ];


    // -------------------------------------------------------------------------------------------------------------------------------------

    let [dataSource, setDataSource] = useState(new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
    }));

    let [orders, setOrders] = useState([]); // 列表初始化

    let [records, setRecords] = useState({}); //  后台返回的分页数据

    let [word, setWord] = useState("加载中..."); // 提示语

    let [isLoading, setisLoading] = useState(true); // loading 切换


    // 初始化数据
    function getOrders (pageNum, pageSize) {
        GetPublishedOrders({ tutor_id: userInfo.id, pageNum: pageNum, pageSize: pageSize }).then(res => {
            if (res.code == '000000') {
                setRecords(res.responseData);
                setOrders(res.responseData.dataList);
                let d = dataSource.cloneWithRows(res.responseData.dataList);
                setDataSource(d);
                setisLoading(false);
                if (!!res.responseData.dataList && res.responseData.dataList.length > 0) {
                    setWord("已加载");
                } else {
                    setWord("亲，没有更多了");
                }
            }
        }).catch(err => {
            console.log(err)
        })
    }

    function getOrders1 (pageNum, pageSize) {  // 历史订单
        GetHistoryOrders({ tutor_id: userInfo.id, pageNum: pageNum, pageSize: pageSize }).then(res => {
            if (res.code == '000000') {
                setRecords(res.responseData);
                setOrders(res.responseData.dataList);
                let d = dataSource.cloneWithRows(res.responseData.dataList);
                setDataSource(d);
                setisLoading(false);
                if (!!res.responseData.dataList && res.responseData.dataList.length > 0) {
                    setWord("已加载");
                } else {
                    setWord("亲，没有更多了");
                }
            }
        }).catch(err => {
            console.log(err)
        })
    }

    //加载数据
    let onEndReached = (event) => {
        if (isLoading || records.pageIndex === records.totalPage) {
            setWord("亲，没有更多了");
            return;
        } else {
            setisLoading(true);
            setWord("加载中...");

            console.log('tabIndex ----->>>', tabIndex)

            if (tabIndex == 0) { // 报名订单
                GetPublishedOrders({ tutor_id: userInfo.id, pageNum: records.pageIndex + 1, pageSize: 10 }).then(res => {
                    if (res.code == '000000') {
                        setRecords(res.responseData);
                        setOrders(res.responseData.dataList);
                        let d = dataSource.cloneWithRows(res.responseData.dataList);
                        setDataSource(d);
                        setisLoading(false);
                        if (!!res.responseData.dataList && res.responseData.dataList.length > 0) {
                            setWord("已加载");
                        } else {
                            setWord("亲，没有更多了");
                        }
                    }
                }).catch(err => {
                    console.log(err)
                })
            } else if (tabIndex == 2) { // 历史订单
                GetHistoryOrders({ tutor_id: userInfo.id, pageNum: records.pageIndex + 1, pageSize: 10 }).then(res => {
                    if (res.code == '000000') {
                        setRecords(res.responseData);
                        setOrders(res.responseData.dataList);
                        let d = dataSource.cloneWithRows(res.responseData.dataList);
                        setDataSource(d);
                        setisLoading(false);
                        if (!!res.responseData.dataList && res.responseData.dataList.length > 0) {
                            setWord("已加载");
                        } else {
                            setWord("亲，没有更多了");
                        }
                    }
                }).catch(err => {
                    console.log(err)
                })
            }
        }
    };


    const separator = (sectionID, rowID) => (
        <div
            key={`${sectionID}-${rowID}`}
            style={{
                backgroundColor: '#F5F5F9',
                height: 8,
                borderTop: '1px solid #ECECED',
                borderBottom: '1px solid #ECECED',
            }}
        />
    );


    const row = (rowData, sectionID, rowID) => {

        //根据状态展示不同内容
        // if (rowData.status === ORDER_STATUSES.FINISHED) {/

        return (
            <div key={rowID} style={{ padding: '0 15px' }}>
                <Item
                    arrow="horizontal"
                    key={rowData.id}
                    multipleLine
                    onClick={() => {
                        props.history.push({
                            pathname: '/orderDetails',
                            data: rowData
                        })
                    }}
                    platform="android"
                >
                    {rowData.subjects}
                    <strong style={{ color: 'red', float: 'right' }}>{rowData.brokerage_fee}</strong>
                    <Brief>
                        工作时段: {rowData.learn_hours}
                        <br />
                        工作地址: {rowData.learn_address}
                        <br />
                        {rowData.demand}
                    </Brief>
                </Item>
            </div>
        );
        // }

    };

    // -------------------------------------------------------------------------------------------------------------------------------------

    // 报名订单
    function handleListFn (data, type) {
        return data.map((item, index) => {
            item._type = type; //  订单类型
            return (
                <Item
                    arrow="horizontal"
                    key={item.id}
                    multipleLine
                    onClick={() => {
                        props.history.push({
                            pathname: '/orderDetails',
                            data: item
                        })
                    }}
                    platform="android"
                >
                    {item.subjects}
                    <strong style={{ color: 'red', float: 'right' }}>{item.brokerage_fee}</strong>
                    <Brief>
                        工作时段: {item.learn_hours}
                        <br />
                        工作地址: {item.learn_address}
                        <br />
                        {item.demand}
                    </Brief>
                </Item>
            )
        })
    }

    // 待定订单
    function handlePendingListFn (data) {
        return data.map((item, index) => {
            item._type = 'pending'; //  待定订单
            return (
                <Item
                    arrow="horizontal"
                    key={item.id}
                    multipleLine
                    onClick={() => {
                        props.history.push({
                            pathname: '/orderDetails',
                            data: item
                        })
                    }}
                    platform="android"
                >
                    {item.subjects}
                    <strong style={{ color: 'red', float: 'right' }}>{item.brokerage_fee}</strong>
                    <Brief>
                        工作时段: {item.learn_hours}
                        <br />
                        工作地址: {item.learn_address}
                        <br />
                        {item.demand}
                    </Brief>
                </Item>
            )
        })
    }



    // 家教查看已经发布的订单  【选择报名的订单】
    let handleGetPublishedOrders = () => {
        let postData = {
            pageSize: 10,
            pageNum: 1
        }
        GetPublishedOrders(postData).then(res => {
            if (res.code == '000000') {

                let d = dataSource.cloneWithRows(orders);
                setDataSource(d);
                setisLoading(false);
                if (!!res.responseData.dataList && res.responseData.dataList.length > 0) {
                    setWord("已加载");
                } else {
                    setWord("亲，没有更多了");
                }

                // setPublishedOrdersList(res.responseData.dataList)
            }
        }).catch(err => {

        })
    }

    // 家教查看待定订单列表  【选中后等待家长确认订单】
    let handleGetProducingApplies = () => {
        let postData = {
            tutor_id: userInfo.id
        }

        GetProducingApplies(postData).then(res => {
            if (res.code == '000000') {
                setPendingList(res.responseData)
            }
        }).catch(err => {

        })
    }

    // 家教查看 正在教学  【正在教学的订单】
    let handleGetWorkingOrders = () => {
        let postData = {
            tutor_id: userInfo.id
        }

        GetWorkingOrders(postData).then(res => {
            if (res.code == '000000') {
                setWorkingList(res.responseData)
            }
        }).catch(err => {

        })
    }

    // 家教查看 历史订单
    let handleGetHistoryOrders = () => {
        let postData = {
            tutor_id: userInfo.id
        }

        GetHistoryOrders(postData).then(res => {
            if (res.code == '000000') {
                setHistoryList(res.responseData.dataList)
            }
        }).catch(err => {

        })
    }


    useEffect(() => {
        // handleGetPublishedOrders();
        handleGetProducingApplies();
        handleGetWorkingOrders();
        // handleGetHistoryOrders()

        getOrders(1, 10)
    }, []);

    const myImg = src => <img src={src} className="spe am-icon am-icon-md" alt="" />;

    return (
        <div className="orderDetails">
            <div className="page-title  home-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    onLeftClick={() => {
                        props.history.goBack()
                    }}
                >
                    需求列表
                </NavBar>
            </div>

            <div className="page-content  home-content">
                <div className="publish-content-piece">

                    <Tabs tabs={tabs}
                          onChange={(tab, index) => {
                              setTabIndex(index)

                              if (index == 0) {
                                  getOrders(1, 10)

                              } else if (index == 2) {
                                  getOrders1(1, 10)

                              }
                          }}
                    >
                        <div style={{ backgroundColor: '#fff' }}>

                            {
                                // !publishedOrdersList.length
                                //     ?
                                //     <Result
                                //         buttonText={"返回主页"}
                                //         img={myImg(nodata, "none")}
                                //         title=""
                                //         message="暂无数据"
                                //         buttonType="primary"
                                //         onButtonClick={() => props.history.push("/main")}
                                //     />

                                //     :

                                // <List>
                                //     {handleListFn(publishedOrdersList)}

                                // </List>

                                <ListView
                                    dataSource={dataSource}
                                    renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                                        {word}
                                    </div>)}
                                    renderRow={row}
                                    renderSeparator={separator}
                                    className="am-list"
                                    pageSize={4}
                                    onScroll={() => {
                                        console.log('scroll');
                                    }}
                                    style={{
                                        height: "calc(100vh - 44px - 44px)",
                                    }}
                                    scrollRenderAheadDistance={500}
                                    onEndReached={onEndReached}
                                    onEndReachedThreshold={10}
                                />
                            }
                        </div>
                        <div style={{ backgroundColor: '#fff' }}>
                            <Card>
                                <Card.Header
                                    title="待定订单"
                                />
                                <Card.Body>
                                    {
                                        !pendingList.length
                                            ?
                                            <Result
                                                buttonText={"返回主页"}
                                                img={myImg(nodata, "none")}
                                                title=""
                                                message="暂无数据"
                                                buttonType="primary"
                                                onButtonClick={() => props.history.push("/main")}
                                            />

                                            :

                                            <List>
                                                {handlePendingListFn(pendingList)}
                                            </List>
                                    }
                                </Card.Body>
                            </Card>
                            <Card>
                                <Card.Header
                                    title="正在教学"
                                />
                                <Card.Body>
                                    {
                                        !workingList.length
                                            ?
                                            <Result
                                                buttonText={"返回主页"}
                                                img={myImg(nodata, "none")}
                                                title=""
                                                message="暂无数据"
                                                buttonType="primary"
                                                onButtonClick={() => props.history.push("/main")}
                                            />

                                            :

                                            <List>
                                                {handleListFn(workingList, 'working')}
                                            </List>
                                    }
                                </Card.Body>
                            </Card>
                        </div>
                        <div>
                            {
                                // !historyList.length
                                //     ?
                                //     <Result
                                //         buttonText={"返回主页"}
                                //         img={myImg(nodata, "none")}
                                //         title=""
                                //         message="暂无数据"
                                //         buttonType="primary"
                                //         onButtonClick={() => props.history.push("/main")}
                                //     />

                                //     :

                                //     <List>
                                //         {handleListFn(historyList, 'history')}

                                //     </List>

                                <ListView
                                    dataSource={dataSource}
                                    renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                                        {word}
                                    </div>)}
                                    renderRow={row}
                                    renderSeparator={separator}
                                    className="am-list"
                                    pageSize={4}
                                    style={{
                                        height: "calc(100vh - 44px - 44px)",
                                    }}
                                    onScroll={() => {
                                        console.log('scroll');
                                    }}
                                    scrollRenderAheadDistance={500}
                                    onEndReached={onEndReached}
                                    onEndReachedThreshold={10}
                                />
                            }
                        </div>
                    </Tabs>
                </div>
            </div>
        </div>);


}

OrderList = createForm()(OrderList);

export default OrderList;